package com.printeverywhere.action;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.hadoop.conf.Configuration;
import org.apache.nutch.searcher.Hit;
import org.apache.nutch.searcher.HitDetails;
import org.apache.nutch.searcher.Hits;
import org.apache.nutch.searcher.NutchBean;
import org.apache.nutch.searcher.Query;
import org.apache.nutch.util.NutchConfiguration;

import com.printeverywhere.dto.NutchSearch;

public class NutchSearchAction extends FrontBaseSupport {
	/**
	 *
	 */
	private static final long serialVersionUID = 1L;
	private String nutchSearchString;
	private int maxHits = 1000;
	private NutchSearch nutchSearch = new NutchSearch();
	private List<NutchSearch> resultsList = new ArrayList<NutchSearch>();

	public NutchSearchAction() {
		super(true, false);
	}

	public String execute() throws Exception {
		Configuration nutchConf = NutchConfiguration.create();
		NutchBean nutchBean = new NutchBean(nutchConf);
		Query nutchQuery = Query.parse(nutchSearchString, nutchConf);
		Hits nutchHits = nutchBean.search(nutchQuery, maxHits);
		System.out.println("Found " + nutchHits.getLength() + " hits\n");

		for (int i = 0; i < nutchHits.getLength(); i++) {
			Hit hit = nutchHits.getHit(i);
			HitDetails details = nutchBean.getDetails(hit);
			NutchSearch nutchSearch = new NutchSearch();
			nutchSearch.setTitle(details.getValue("title"));
			nutchSearch.setUrl(details.getValue("url"));
			nutchSearch.setSummary(nutchBean.getSummary(details, nutchQuery)
					.toString());
			System.out.println("Title is: " + nutchSearch.getTitle());
			System.out.println("(" + nutchSearch.getUrl() + ")");
			nutchSearch.setDate(new java.util.Date(nutchBean
					.getFetchDate(details)));
			System.out.println("Date Fetched: " + nutchSearch.getDate());
			System.out.println(nutchSearch.getSummary() + "\n");
			System.out.println("----------------------------------------");
			resultsList.add(nutchSearch);
			System.out.println("=====>  " +resultsList.get(i).getUrl());
		}
		System.out.println("1");
		return SUCCESS;
	}

	public String getNutchSearchString() {
		return nutchSearchString;
	}

	public void setNutchSearchString(String nutchSearchString) {
		this.nutchSearchString = nutchSearchString;
	}

	public int getMaxHits() {
		return maxHits;
	}

	public void setMaxHits(int maxHits) {
		this.maxHits = maxHits;
	}

	public List<NutchSearch> getResultsList() {
		return resultsList;
	}

	public void setResultsList(List<NutchSearch> resultsList) {
		this.resultsList = resultsList;
	}
}
